package com.siyoumi.app.modules.accsuper_admin.service;

import com.siyoumi.app.modules.accsuper_admin.vo.SysAccsuperConfigVo;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XBean;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.entity.SysAccount;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.service.SysAccountService;
import com.siyoumi.service.SysAccsuperConfigService;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

//项目
@Slf4j
@Service
public class SvcSysAccspuerConfig {
    static public SvcSysAccspuerConfig getBean() {
        return XSpringContext.getBean(SvcSysAccspuerConfig.class);
    }

    static public SysAccsuperConfigService getApp() {
        return SysAccsuperConfigService.getBean();
    }


    public XReturn addAccsuper(SysAccsuperConfigVo vo, Boolean wxopen) {
        SysAccsuperConfig entity = XApp.getTransaction().execute(status -> {
            SysAccsuperConfig entityConfig = getApp().first(vo.getAcc_uid());

            log.debug("开始保存");
            SysAccsuperConfig entityConfigUpdate = new SysAccsuperConfig();
            entityConfigUpdate.setAconfig_id(vo.getAcc_uid());
            entityConfigUpdate.setAconfig_x_id(entityConfigUpdate.getAconfig_id());
            entityConfigUpdate.setAconfig_type(vo.getAconfig_type());
            entityConfigUpdate.setAconfig_token(XDate.toS(XDate.now()) + "");
            if (wxopen) {
                log.debug("开放平台授权");
                entityConfigUpdate.setAconfig_wxopen(1);
            }
            getApp().saveOrUpdatePassEqualField(entityConfig, entityConfigUpdate);

            if (entityConfig == null) {
                log.debug("保存超管登陆账号");
                SysAccountService appAcc = SysAccountService.getBean();
                SysAccount entityAcc = appAcc.loadEntity(XBean.toMap(vo));
                entityAcc.setAcc_role("super_admin");
                entityAcc.setAcc_x_id(entityConfigUpdate.getAconfig_id());
                entityAcc.setAcc_pwd(XApp.encPwd(entityConfigUpdate.getAconfig_id(), vo.getAcc_pwd()));
                entityAcc.setAutoID();
                appAcc.save(entityAcc);

                log.debug("保存开发者账号");
                SysAccount entityAccDev = new SysAccount();
                entityAccDev.setAcc_role("dev");
                entityAccDev.setAcc_uid("dev");
                entityAccDev.setAcc_name("开发者");
                entityAccDev.setAcc_x_id(entityAcc.getAcc_x_id());
                //当前时间年月日
                entityAccDev.setAcc_pwd(XApp.encPwd(entityConfigUpdate.getAconfig_id(), XDate.now().format(XDate.yyyyMMdd_PATTERN)));
                entityAccDev.setAutoID();
                appAcc.save(entityAccDev);
            }

            return entityConfigUpdate;
        });


        XReturn r = XReturn.getR(0);
        r.setData("entity", entity);

        return r;
    }
}
